package com.hcx.poi.xssf.eventmodel;

import java.io.InputStream;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.hcx.excel.xlsx.SheetInfo;
import com.hcx.poi.xssf.eventmodel.workbookhandler.WorkbookSheetHandler;
import com.hcx.xml.sax.XmlElementContentHandler;
import com.hcx.xml.sax.XmlTool;

public abstract class XSSFHelper {
	public static SheetInfo[] getSheetInfos(OPCPackage pkg) {
		try {
			XSSFReader reader = new XSSFReader(pkg);
			InputStream in = reader.getWorkbookData();
			// 初始化 SAX ContentHandler 对象
			XmlElementContentHandler contentHandler = new XmlElementContentHandler();
			WorkbookSheetHandler handler = new WorkbookSheetHandler();
			contentHandler.addElementContentHandler(handler);

			XMLReader parser = XmlTool.getXmlReader();
			parser.setContentHandler(contentHandler);
			parser.parse(new InputSource(in));

			in.close();
			return handler.getSheetInfos();
		} catch (Exception ex) {
			throw new RuntimeException("加载 SheetInfo 失败！", ex);
		}
	}
	
	public static SheetInfo getSheetInfo(String sheetName, OPCPackage pkg){
		SheetInfo[] infos = getSheetInfos(pkg);
		if(infos == null || infos.length < 1){
			return null;
		}
		
		for(SheetInfo info : infos){
			if(info.getName().equals(sheetName)){
				return info;
			}
		}
		return null;
	}

	/**
	 * 转换 Sheet 中列的字母索引为数字索引。A = 0
	 * 
	 * @param r
	 * @return
	 */
	static public int getColumnIndex(String r) {
		String colIndex = r.split("[0-9]+")[0];
		if (colIndex.length() != 1) {
			throw new UnsupportedOperationException(String.format(
					"暂时不支持(%s)列的解析！", colIndex));
		}
		char c = colIndex.charAt(0);
		int result = (int) c;
		result -= 65;
		return result;
	}
}
